
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using ScrewTurn.Wiki.PluginFramework;

namespace ScrewTurn.Wiki {

	public partial class Login : BasePage {

		private const string LoginKey = "LoginKey";
		private const string Username = "Username";
		private const string Logout = "Logout";

        protected void Page_Load(object sender, EventArgs e) {

            // SUEETIE Modified - Redirecting to central membership login page
            // For security purposes, because wiki users share a common password, 
            //    do auto-redirect to site-wide login page when users are established in wiki

            Response.Redirect("/Members/Login.aspx?Logout=1");

            Page.Title = Resources.Messages.LoginTitle + " - " + Settings.WikiTitle;

			lblResult.Text = "";
			lblResult.CssClass = "";

			lblLostPassword.Text = Resources.Messages.LostPassword;

			PrintLoginNotice();

			// In case of provider supporting autologin, a user might not be able to logout
			// without applying a "filter" because the provider might keep logging she in.
			// When she clicks Logout and redirects to Login.aspx?Logout=1 a flag is set,
			// avoiding autologin for the current session
			if(Request["Logout"] != null) Session[Logout] = true;

			// All the following logic must be executed only on first page request
			if(Page.IsPostBack) return;

			if(SessionFacade.LoginKey == null && Request.Cookies[Settings.LoginCookieName] != null) {
				string username = Request.Cookies[Settings.LoginCookieName].Values[Username];
				string key = Request.Cookies[Settings.LoginCookieName].Values[LoginKey];

				// Try cookie login
				UserInfo user = Users.Instance.TryCookieLogin(username, key);
				if(user != null) {
					SetupSession(user);
					Log.LogEntry("User " + user.Username + " logged in through cookie", EntryType.General, "SYSTEM");
					TryRedirect(false);
				}
				else {
					// Cookie is not valid, delete it
					SetLoginCookie("", "", DateTime.Now.AddYears(-1));
				}
			}
			else if(Session[Logout] == null) { // Check for filtered autologin
				// If no cookie is available, try to autologin through providers
				UserInfo user = Users.Instance.TryAutoLogin(Context);
				if(user != null) {
					SetupSession(user);
					Log.LogEntry("User " + user.Username + " logged in via " + user.Provider.GetType().ToString() + " autologin", EntryType.General, "SYSTEM");
					TryRedirect(false);
				}
			}

			if(SessionFacade.LoginKey != null) {
				mlvLogin.ActiveViewIndex = 0;
				lblLogout.Text = "<b>" + SessionFacade.Username + "</b>, " + lblLogout.Text;
			}
			else {
				if(Request["PasswordReset"] != null) mlvLogin.ActiveViewIndex = 2;
				else mlvLogin.ActiveViewIndex = 1;
			}

            if(Request["Activate"] != null && !Page.IsPostBack) {
				Users u = Users.Instance;
                for(int i = 0; i < u.AllUsers.Count; i++) {
                    if(Tools.ComputeSecuredUsernameHash(u.AllUsers[i].Username).Equals(Request["Activate"])) {
                        Log.LogEntry("Account activation requested for " + u.AllUsers[i].Username, EntryType.General, "SYSTEM");
                        if(u.AllUsers[i].Active) {
							lblResult.CssClass = "resultok";
							lblResult.Text = "<br /><br />" + Resources.Messages.AccountAlreadyActive;
                            return;
                        }
                        if(u.AllUsers[i].DateTime.AddHours(24).CompareTo(DateTime.Now) < 0) {
                            // Too late
							lblResult.CssClass = "resulterror";
							lblResult.Text = "<br /><br />" + Resources.Messages.AccountNotFound;
                            // Delete user (is this correct?)
                            u.RemoveUser(u.AllUsers[i]);
                            return;
                        }
                        // Activate User
						u.SetActivationStatus(u.AllUsers[i], true);
						lblResult.CssClass = "resultok";
						lblResult.Text = "<br /><br />" + Resources.Messages.AccountActivated;
                        return;
                    }
                }
				lblResult.CssClass = "resulterror";
				lblResult.Text = "<br /><br />" + Resources.Messages.AccountNotActivated;
                return;
            }
        }

		public void PrintLoginNotice() {
			string n;
			if(!Content.PseudoCache.TryGetValue("LoginNotice", out n)) {
				n = Tools.LoadFile(Settings.LoginNoticeFile);
				if(!string.IsNullOrEmpty(n)) {
					n = Formatter.Format(n, null);
					Content.PseudoCache["LoginNotice"] = n;
				}
			}
			if(!string.IsNullOrEmpty(n)) lblDescription.Text = n;
		}

		private void SetupSession(UserInfo user) {
			SessionFacade.LoginKey = Users.Instance.ComputeLoginKey(user.Username);
			SessionFacade.Username = user.Username;
			SessionFacade.Admin = user.Admin;
			Session[Logout] = null; // No session facade because this key is used only in this page
		}

		private void TryRedirect(bool goHome) {
			if(Request["Redirect"] != null) Response.Redirect(Request["Redirect"]);
			else if(goHome) Response.Redirect("Default.aspx");
		}

		private void SetLoginCookie(string username, string loginKey, DateTime expiration) {
			HttpCookie cookie = new HttpCookie(Settings.LoginCookieName);
			cookie.Expires = expiration;
			cookie.Path = Settings.CookiePath;
			cookie.Values.Add(LoginKey, loginKey);
			cookie.Values.Add(Username, username);
			Response.Cookies.Add(cookie);
		}

        protected void btnLogin_Click(object sender, EventArgs e) {

			UserInfo user = Users.Instance.TryLogin(txtUsername.Text, txtPassword.Text);
			if(user != null) {
				string loginKey = Users.Instance.ComputeLoginKey(user.Username);
				if(chkRemember.Checked) {
					SetLoginCookie(user.Username, loginKey,
						DateTime.Now.AddYears(1));
				}
				SetupSession(user);
				Log.LogEntry("User " + user.Username + " logged in", EntryType.General, "SYSTEM");
				TryRedirect(true);
			}
			else {
				lblResult.CssClass = "resulterror";
				lblResult.Text = "<br /><br />" + Resources.Messages.WrongUsernamePassword;
			}

        }

        protected void btnLogout_Click(object sender, EventArgs e) {
			Users.Instance.NotifyLogout(SessionFacade.Username);
            Session.Abandon();
			SetLoginCookie("", "", DateTime.Now.AddYears(-1));
			Log.LogEntry("User " + SessionFacade.Username + " logged out", EntryType.General, "SYSTEM");
            // SUEETIE Modified - Redirecting to central membership login page
            Response.Redirect("/Members/Login.aspx?Logout=1");
        }

        protected void btnResetPassword_Click(object sender, EventArgs e) {
			Users users = Users.Instance;
            UserInfo u = users.Find(txtUsernameReset.Text);
            if(u != null) {
				if(u.Email.Equals(txtEmailReset.Text)) {
					users.ResetPassword(u);
					Log.LogEntry("Password reset requested for " + txtUsernameReset.Text, EntryType.General, "SYSTEM");
				}
            }
			lblResult.CssClass = "resultok";
			lblResult.Text = "<br /><br />" + Resources.Messages.PasswordReset;
			txtUsernameReset.Text = "";
			txtEmailReset.Text = "";
        }

    }

}
